/**
 * Created by Nico on 2016/1/5.
 */

grApp.controller('DataBaseCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){

    $scope.manageCities = [];
    //添加省
    $scope.save = function(){
        DatabaseFactory.save_area({province:$scope.province,parentid:0}).then(function(data){
            console.log(data);
        });
    };

    //$scope.mycity = '北京';
    //添加城市
    DatabaseFactory.show_area_list({parentid:0,status:1}).then(function(data){
        console.log(data);
        $scope.Provinces = data;
    });

    $scope.save_city=function(){
        DatabaseFactory.save_area({city:$scope.city, parentid:$scope.myProvince.id}).then(function(data){
            console.log(data);
        });
    };

    $scope.user ={name:'',password:'',surepass:'',email:''};
    //添加用户
    $scope.save_user = function(){
        console.log( $scope.manageCities);
        var user_info = {username:$scope.user.name,password:$scope.user.password,email:$scope.user.email,status:1,}
        //{user_info:user_info, user_area_relation:$scope.manageCities}
        //alert(JSON.stringify({user_info:user_info, user_area_relation:$scope.manageCities}));
        DatabaseFactory.save_user_with_area({user_info:user_info, user_area_relation:$scope.manageCities}).then(function(data){
            if(data.code === 0){
                showTips('success','添加成功');
            }else{
                showTips('error','添加失败');
            }
        });
    };
    $scope.changeCity = function(){
        DatabaseFactory.show_area_list({parentid:$scope.myProvince.id,status:1}).then(function(data){
            $scope.Cities = data;
        });
    };
    var i = 0 ;
    $scope.add_managerCity = function(){
        $scope.manageCities.push($scope.myCity);
    };
}]);
grApp.controller('AddCityCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){

    var city = {};
    //初始化数据
    $scope.load = function(args){
        DatabaseFactory.show_area_list({parentid:0,status:1}).then(function(data){
            $scope.Provinces = data;
            if(args){
                //province.province as
                $scope.myProvince = args.pid;
                $scope.city = args.city;
                city['id'] = args.id ;
            }
        });
    };

    //添加城市
    $scope.save_city=function(){
        city['parentid'] = $scope.myProvince ;
        city['city'] = $scope.city;

        DatabaseFactory.save_area(city).then(function(data){
            console.log(data);
        });
    };
}]);

grApp.controller('CityManageCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){
    var chockbox_id = [] ;
    $scope.CityList = [];
    //获取全部城市列表
    $scope.getAllCityList = function(){
        DatabaseFactory.getAllCityList().then(function(data){
            $scope.CityList = data ;
            console.log(data)
        });
    }
    //编辑
    $scope.edit = function(index){
        console.log($scope.CityList[index]);
        //跳转到添加用户页面，默认读取所有数据
        window.location = "/add_or_edit_city?city="+JSON.stringify($scope.CityList[index]);
        //DatabaseFactory.add_or_edit_city($scope.CityList[index]);

    };

    //删除 单个
    $scope.delete = function(index){
        DatabaseFactory.deleteOne_city($scope.CityList[index].id).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                $scope.CityList.splice($scope.CityList.indexOf($scope.CityList[index]),1);
            }
        });
    };
    $scope.deleteAll = function(index){
        var city_ids = []
        for (var i in chockbox_id){
            city_ids.push($scope.CityList[i].id);
        }
        DatabaseFactory.deleteOne_city(city_ids).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                for (var i in chockbox_id){
                    $scope.CityList.splice(i,1);
                }
            }
        });
    };
    //启用
    $scope.inuse = function(){
        //修改status的值
        var city_ids = []
        for (var i in chockbox_id){
            city_ids.push($scope.CityList[i].id);
        }
        //status：-1 已删除，0 被禁用，1 正常，2 未审核
        DatabaseFactory.change_city_status(city_ids,1).then(function(data){
            showTips('success','已启用');
            for (var i in chockbox_id){
                $scope.CityList[i].status = 1;
            }
        });
    };
    $scope.unuse=function(){
        //修改status的值
        var city_ids = []
        for (var i in chockbox_id){
            city_ids.push($scope.CityList[i].id);
        }
        //status：-1 已删除，0 被禁用，1 正常，2 未审核
        DatabaseFactory.change_city_status(city_ids,0).then(function(data){
            showTips('success','已禁用');
            for (var i in chockbox_id){
                $scope.CityList[i].status = 0 ;
            }
        });
    };
    //chekbox选中
    $scope.check = function($event,index){
        var checked = $event.target;
        if(checked.checked){
            chockbox_id.push(index);
        }else{
            chockbox_id.splice(chockbox_id.indexOf(index),1);
        }
        console.log(chockbox_id);
    };
    $scope.getAllCityList();
}]);
grApp.controller('AddUserCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){
    $scope.manageCities = [];
    $scope.manageCities_ids = [] ;

    $scope.user ={name:'',password:'',surepass:'',email:''};
    var user_info = {} ;
    $scope.load = function(args){
        DatabaseFactory.show_area_list({parentid:0,status:1}).then(function(data){
            $scope.Provinces = data;
            if(args){
                //province.province as
                $scope.myProvince = args.pid;
                $scope.city = args.city;
                $scope.user = {name:args.username,password:args.password,surepass:args.password,email:args.email};
                user_info['id'] = args.id ;
            }
        });
    };
    //添加用户
    $scope.save_user = function(){
        user_info['username'] = $scope.user.name;
        user_info['password'] =$scope.user.password;
        user_info['email'] = $scope.user.email;
        user_info['status'] =1;
        DatabaseFactory.save_user_with_area({user_info:user_info, user_area_relation:$scope.manageCities_ids}).then(function(data){
            if(data.code === 0){
                showTips('success','添加成功');
            }else{
                showTips('error','添加失败');
            }
        });
    };
    $scope.changeCity = function(){
        DatabaseFactory.show_area_list({parentid:$scope.myProvince.id,status:1}).then(function(data){
            $scope.Cities = data;
        });
    };
    var i = 0 ;
    $scope.add_managerCity = function(){
        if($scope.manageCities.indexOf($scope.myCity)!=-1){
            showTips('wrong','元素已存在，请勿重复添加');
        }else{
            $scope.manageCities.push($scope.myCity);
            $scope.manageCities_ids.push($scope.myCity.id);
        }

    };
    $scope.delete_alert = function(index){
        console.log(index);
        $scope.manageCities.splice($scope.manageCities_ids.indexOf(index),1);
        $scope.manageCities_ids.splice($scope.manageCities_ids.indexOf(index),1);
        console.log($scope.manageCities_ids);
    }
}]);
grApp.controller('UserManageCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){
    var chockbox_id = [] ;
    $scope.UserList=[];
    DatabaseFactory.show_auth_list().then(function(data){
        $scope.UserList=data;
        console.log(data);
    }).catch(function(err){
        console.log(err);
    });
    //编辑
    $scope.edit = function(index){
        console.log($scope.UserList[index]);
        //跳转到添加用户页面，默认读取所有数据
        window.location = "/add_or_edit_user?user="+JSON.stringify($scope.UserList[index]);

    };

    //删除 单个
    $scope.delete = function(index){
        DatabaseFactory.deleteOne_user($scope.UserList[index].id).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                console.log($scope.UserList);
                $scope.UserList.splice($scope.UserList.indexOf($scope.UserList[index]),1);
                console.log($scope.UserList);
            }
        });
    };
    $scope.deleteAll = function(index){
        var user_ids = []
        for (var i in chockbox_id){
            user_ids.push($scope.UserList[i].id);
        }
        DatabaseFactory.deleteOne_user(user_ids).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                for (var i in chockbox_id){
                    $scope.UserList.splice(i,1);
                }
            }
        });
    };
    //启用
    $scope.inuse = function(){
        //修改status的值
        var user_ids = []
        for (var i in chockbox_id){
            user_ids.push($scope.UserList[i].id);
        }
        //status：-1 已删除，0 被禁用，1 正常，2 未审核
        DatabaseFactory.change_user_status(user_ids,1).then(function(data){
            showTips('success','已启用');
            for (var i in chockbox_id){
                $scope.UserList[i].status = 1;
            }
        });
    };
    $scope.unuse=function(){
        //修改status的值
        var user_ids = []
        for (var i in chockbox_id){
            user_ids.push($scope.UserList[i].id);
        }
        //status：-1 已删除，0 被禁用，1 正常，2 未审核
        DatabaseFactory.change_user_status(user_ids,0).then(function(data){
            showTips('success','已禁用');
            for (var i in chockbox_id){
                $scope.UserList[i].status = 0 ;
            }
        });
    };
    //chekbox选中
    $scope.check = function($event,index){
        var checked = $event.target;
        if(checked.checked){
            chockbox_id.push(index);
        }else{
            chockbox_id.splice(chockbox_id.indexOf(index),1);
        }
        console.log(chockbox_id);
    };
}]);
/**
 * Update by Nico on 2016/1/12.
 */
grApp.controller('ConfigManageCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){
    //获取config表中的所有数据
    $scope.init = function(){
        DatabaseFactory.show_config_list().then(function(data){
            $scope.Configs = data ;
            console.log($scope.Configs );
        });
    }
    $scope.init();
    //编辑
    $scope.edit = function(index){
        console.log($scope.Configs[index]);
        //跳转到添加用户页面，默认读取所有数据
        window.location = "/add_or_edit_config?config="+JSON.stringify($scope.Configs[index]);
        //DatabaseFactory.add_or_edit_city($scope.CityList[index]);

    };

    //删除 单个
    $scope.delete = function(index){
        DatabaseFactory.deleteOne_config($scope.Configs[index].id).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                $scope.Configs.splice($scope.Configs.indexOf($scope.Configs[index]),1);
            }
        });
    };
    var chockbox_id = [] ;
    $scope.deleteAll = function(index){
        var config_ids = []
        for (var i in chockbox_id){
            config_ids.push($scope.Configs[i].id);
        }
        DatabaseFactory.deleteOne_config(config_ids).then(function(data){
            if(data){
                //删除成功
                showTips('success','删除成功');
                for (var i in chockbox_id){
                    $scope.Configs.splice(i,1);
                }
            }
        });
    };
    //chekbox选中
    $scope.check = function($event,index){
        var checked = $event.target;
        if(checked.checked){
            chockbox_id.push(index);
        }else{
            chockbox_id.splice(chockbox_id.indexOf(index),1);
        }
        console.log(chockbox_id);
    };
}]);
//新增、编辑配置
grApp.controller('AddConfigCtr',['$scope','$http','DatabaseFactory',function($scope,$http,DatabaseFactory){
    //var config = {name:'',title:'',sort:'',type:'',group:'',exta:'',value:'',remark:''}

    $scope.load = function(args){
        $scope.config = args;
    };
    $scope.groups = [{id:1,name:'不分组'},{id:2,name:'基本'},{id:3,name:'内容'},{id:4,name:'用户'},{id:5,name:'系统'}];
    $scope.types = [{id:1,name:'数字'},{id:2,name:'字符'},{id:3,name:'文本'},{id:4,name:'数组'},{id:5,name:'枚举'}];
    //$scope.Cities = [{ id: 1, name: '北京', group: '中国' }, { id: 2, name: '上海', group: '中国' }, { id: 3, name: '广州', group: '中国' }];
    $scope.group_change = function(){
        //alert($scope.myGroup.id);
    }
    $scope.type_change = function(){
        //alert($scope.myType.id);
    }
    //添加
    $scope.save_config =function(){
        console.log($scope.config);
        DatabaseFactory.save_config_list($scope.config).then(function(data){
            alert('保存成功');
        });
    }
}]);

grApp.factory('DatabaseFactory', ['$http', '$q', function ($http, $q) {
    var service = {};
    service.save_area = function (args) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/addProvice',
            params: args
        }).success(function (data, status, headers, config) {
            //console.log(data);
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.show_area_list = function (area) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/show_area_list',
            params:area
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.save_user_with_area = function (args1) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/addUserWithArea',
            params: args1
        }).success(function (data, status, headers, config) {
            //console.log(data);
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.getAllCityList = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/showCityList'
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.show_auth_list = function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/show_auth_list'
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.deleteOne_user = function (ids) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/deleteOne_user',
            params:{ids:ids}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.change_user_status = function (ids,status) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/change_user_status',
            params:{ids:ids,status:status}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.change_city_status = function (ids,status) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/change_city_status',
            params:{ids:ids,status:status}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.deleteOne_city = function (ids) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/basedata/deleteOne_city',
            params:{ids:ids}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    service.add_or_edit_city = function (city) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/add_or_edit_city',
            params:city
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    //configmanage
    service.show_config_list = function (city) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/show_config_list',
            params:city
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };
    service.save_config_list = function (config) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/save_config_list',
            params:{config:config}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    service.deleteOne_config = function (ids) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/delete_config',
            params:{ids:ids}
        }).success(function (data, status, headers, config) {
            deferred.resolve(data);
        }).
            error(function (data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    return service;
}]);

grApp.directive('pwCheck', function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var firstPassword = '#' + attrs.pwCheck;
            $(elem).add(firstPassword).on('keyup', function () {
                scope.$apply(function () {
                    var v = elem.val()===$(firstPassword).val();
                    ctrl.$setValidity('pwmatch', v);
                });
            });
        }
    }
});